<template>
	<view class="base-radio-group">
		<view
			class="base-radio-group__item"
			@click="radioValue = radioValue == item[props.defaultProps.value] ? '' : item[props.defaultProps.value]"
			:class="item[props.defaultProps.value] === radioValue ? 'active' : ''"
			v-for="item in props.options"
			:key="item[props.defaultProps.value]"
			:style="`flex: 0 0 ${props.itemWidth}`"
		>
			{{ item[props.defaultProps.label] }}
		</view>
	</view>
</template>

<script setup>
const emit = defineEmits(['change', 'update:modelValue']);
const props = defineProps({
	options: {
		type: Array,
		default: () => []
	},
	modelValue: {
		type: [String, Number],
		default: null
	},
	itemWidth: {
		type: String,
		default: '48%'
	},
	defaultProps: {
		type: Object,
		default: () => ({
			label: 'name',
			value: 'value'
		})
	}
});

const radioValue = ref(props.modelValue);

watch(
	() => radioValue.value,
	value => {
		const checkItem = props.options.find(item => item[props.defaultProps.value] === value);
		emit('change', checkItem || {});
		emit('update:modelValue', value)
	}
);

watch(
	() => props.modelValue,
	value => {
		radioValue.value = value;
	}, {
		immediate: true
	}
);
</script>

<style lang="scss">
.base-radio-group {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;

	&__item {
		height: 32px;
		line-height: 32px;
		text-align: center;
		background: #ecf5ff;
		font-size: 12px;
		margin-bottom: 8px;
		border-radius: 3px;
		color: #666;

		&.active {
			color: #fff;
			background: #4c7bfd;
		}
	}
}
</style>
